<%@ page contentType="text/html; charset=UTF-8"%>
<%@ page import="com.sinodata.bsm.common.constants.ResConstants"%>
<%@ include file="../include/taglib.jsp"%>
<%@ page import = "java.util.*" %>
<%@ page import="com.sinodata.bsm.common.vo.Res"%>
<%@ page import = "com.sinodata.bsm.common.vo.Probe" %>
<%@ page import="com.sinodata.bsm.center.purview.FunctionConstants"%>
<%@ page import="com.sinodata.bsm.center.purview.UserFunctionValidate"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
	<head>
		<title>资源查询</title>
		<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
		<meta http-equiv="pragma" content="no-cache" />
		<meta http-equiv="cache-control" content="no-cache" />
		<meta http-equiv="expires" content="0" />
		<%@ include file="../include/common.jsp"%>
		<%@ include file="../include/table.jsp"%>
		<%@ include file="../include/jbox.jsp"%>
		<%@ include file="../include/tree.jsp"%>
<style>
	.health_0{
		color: #2cb900;
	}
	.health_1{
		color: #56a8f4;
	}
	.health_2{
		color: #dede03;
	}
	.health_3{
		color: #ff9937;
	}
	.health_4{
		color: #ce110f;
	}
</style>

<script type="text/javascript">
    refreshTable=function(scope,scopeName){
    	if(scopeName == ''){
			$("#dimensionDiv").css({"display":"none"});
		}else{
			$("#dimensionDiv").css({"display":""});
		}
		$("#dimensionSearch").html(scopeName);
		$("#dimension").val(scope);
	}
    function delDiv(id){
		window.parent.delDiv(id);
	}
    	function showMenu() {
			var cityObj = $("#resTypeName");
			var cityOffset = $("#resTypeName").offset();
			$("#menuContent").css({left:cityOffset.left + "px", top:cityOffset.top + cityObj.outerHeight() + "px"}).slideDown("fast");
			
			$("body").bind("mousedown", onBodyDown);
		}
		function hideMenu() {
			$("#menuContent").fadeOut("fast");
			$("body").unbind("mousedown", onBodyDown);
		}
		function onBodyDown(event) {
			if (!(event.target.id == "menuBtn" || event.target.id == "resTypeId" || event.target.id == "menuContent" || $(event.target).parents("#menuContent").length>0)) {
				hideMenu();
			}
		}
		function onClick(e, treeId, treeNode) {
			var zTree = $.fn.zTree.getZTreeObj("resTypeTree"),
			nodes = zTree.getSelectedNodes(),
			v = "";
			
			var resTypeId = nodes[0].id;
			selfFound = nodes[0].selfFound;
			
			hideMenu();
			$("#resTypeId").attr("value", resTypeId);
			$("#resTypeName").attr("value", nodes[0].name);
			$("#resTypeName").blur();
		}
		
		var setting = {
			async: {
				enable: true,
				url:"res-type!typeTree.action",
				dataType: "text",
				autoParam:["id"]
			},
			callback: {
				onClick: onClick
			},
			view: {
				dblClickExpand: false,
				showLine: false
			}
		};
    
    	$(document).ready(function(){
	    	if(parent.document.getElementById("scopeName").value == ''){
				$("#dimensionDiv").css({"display":"none"});
			}else{
				$("#dimensionDiv").css({"display":""});
			}
    		$("#dimensionSearch").html(parent.document.getElementById("scopeName").value);
    		$("#dimension").val(parent.document.getElementById("scope").value);
    	$.fn.zTree.init($("#resTypeTree"),setting);
    	
    	
    	var oTable=$("#resList").dataTable({
    			"bProcessing": true, 
				"bServerSide": true,
				"sServerMethod": 'POST',
				"sAjaxSource":'res!query.action',
				"bPaginate":true,
				"bSort": true,
				"bFilter":false,
				"bJQueryUI":false,
				"sPaginationType": 'full_numbers',
				"sDom": 'rt <"bottom"flpi>',
				"iDisplayLength":10,
				"aLengthMenu": [[10, 20, 30, 50,100], [10, 20, 30,50,100]],
				"aoColumns":[
					{"mDataProp":"checkbox","bSortable": false},
					{"mDataProp":"resTypeName","bSortable": false},
					{"mDataProp":"ip","bSortable": false},
					{"mDataProp":"healthStatusStr","bSortable": false,"fnCreatedCell":function(nTd, sData, oData, iRow, iCol){
						$(nTd).html("<div style='text-align:center' class=health_"+oData.healthStatus+">"+sData+"</div>");
					}},
					{"mDataProp":"probeName","bSortable": false},
					{"mDataProp":"resName","bSortable": false,"fnCreatedCell":function(nTd, sData, oData, iRow, iCol){
						$(nTd).html("<div  name='details' >"+sData+"</div>");
					}},
					{"mDataProp":"statu","bSortable": false},
					{"mDataProp":"resTypeId","bVisible":false},
					{"mDataProp":"id","bVisible":false},
					{"mDataProp":"desc","bVisible":false}
				],
				"oLanguage": { 
					 		"sLengthMenu": "每页 _MENU_ 条",
			 		 		"sZeroRecords": "  ",
							"sInfo": "当前从 _START_ 到 _END_ 条,共 _TOTAL_ 条记录", 
							"sInfoEmpty": "没有找到记录",
							"oPaginate":{"sFirst":" ","sPrevious":" ","sNext":" ","sLast":" "}
				},
				"fnServerParams":function(aoData){
					var id = $("#id").val();
					var ip = $('#ip').val();
					var name = $('#name').val();
					var probeId = $('#probeId').val();
					var paused   = $("input[name='paused']:checked");
					var healthStatus = $("input[name='healthStatus']:checked");
					//维度范围
			    	if('$("#dimension").val()' != ''){
			    		aoData.push({'name':'dimension','value':$("#dimension").val()});
			    	}
					
					if(id!=''){
						aoData.push({"name":"FILTER_EQ_Iid","value":id});
					}
					
					if(ip!=''){
						aoData.push({"name":"FILTER_LIKE_Sip","value":ip});
					}
					
					if(name!=''){
						aoData.push({"name":"FILTER_LIKE_Sname","value":name});
					}
					
					if(probeId!=''){
						aoData.push({"name":"FILTER_EQ_Iprobe_Id","value":probeId});
					}
					
					var pausedValue ='';
					$.each(paused,function(index,ob){
						pausedValue += ob.value;
						
						if(index!=(paused.length-1)){
							pausedValue +=',';
						}
					});
					if(paused.length>0){
					  aoData.push({"name":"FILTER_IN_Ipaused","value":pausedValue==''?'null':pausedValue});
					}
				
					var statuValue = '';
					$.each(healthStatus,function(index,ob){
						statuValue += ob.value;
						
						if(index!=(healthStatus.length-1)){
							statuValue+=',';
						}
					});
					
					if(healthStatus.length>0){
						aoData.push({"name":"FILTER_IN_Ihealth_status","value":statuValue==''?'null':statuValue});
					}
				}
    		});
    		$('#resList tbody td :checkbox').live('click', function (e) {
    			var nTr = $(this).parents('tr')[0]; 
   		    	showDetailFlag = true;
    			   if ($(nTr).hasClass('row_selected')) {
					  	$(nTr).removeClass('row_selected'); 
				  }else
				  {
				  		$(nTr).addClass('row_selected'); 
				 }
				 if(!$(this).attr("checked")){
				 	$('#allCheck').attr("checked",false);
				 }
    		});
    		showDetailFlag = false;
    		$('#resList tbody tr').live('click', function (e) {
				 if(showDetailFlag){
				 	showDetailFlag = false;
				 	return;
				 }
				 var nTds = $('td', this);
			      if ( $(this).hasClass('row_selected') ) {
					  	$(this).removeClass('row_selected'); 
				  }else
				  {
				  		$(this).addClass('row_selected'); 
				 }
				
				//显示资源明细
    			if ( oTable.fnIsOpen(this) ) {
    				oTable.fnClose( this ); 
    			}else{
    				oTable.fnOpen(this,fnFormatDetails(oTable,this),'details');
    			}
			});
			
			
			//给回车键绑定一个事件
			$("#searchParameter").bind('keydown',function(event,a){
				if(event.keyCode==13){
					search();
				}
			});
    		
    	});
    	
    	
    	function fnFormatDetails ( oTable, nTr ) {  
    		var aData = oTable.fnGetData( nTr ); 
    		if(aData==null){
    			return ;
    		}
    		var sOut = '<table cellpadding="5"  cellspacing="0" border="0" style="padding-left:50px;">'; 
    		 $.ajax({
					type:'post',
					url:'attribute!attributes.action',
					data:{resId:aData.id,resTypeId:aData.resTypeId},
					global:false,
					async:false,
					cache:false,
					dataType:'json',
					success:function(data,textStatus){
							$.each(data,function(index,ob){
								sOut += '<tr><td>'+ob.name+':</td><td>'+ob.attrValue+'</td></tr>';     
							});
					},
					error:function(errorOb,type){
						getTopWin(window).getMessageBox().alert('服务器内部错误,请联系管理员','错误');
					}
			  });
			  	 sOut += '<tr><td>描述:</td><td>'+aData.desc+'</td></tr>'; 
    			 sOut += '</table>';           
    			 return sOut; 
       } 
       
       function allSelected(){
			var dt_check_all = $('#allCheck').attr("checked");
	  	    var allCheckbox = $("input[name='resCheck']");
  	    	if(dt_check_all)
  	    	{
  	    		allCheckbox.attr("checked",allCheckbox);  //全选
  	    		$('#resList tbody tr').addClass('row_selected');  //背景色全选
  	    	}else
  	    	{
  	    		allCheckbox.attr("checked",false);   //取消全选
  	    		$('#resList tbody tr').removeClass('row_selected');  //背景色取消
  	    	}
		}
		
		function search(){
			var oTable=	$("#resList").dataTable();
			oTable.fnPageChange("first",true);
		}
		function openIpChangeWindow(){
			var selected = $("input[name='resCheck']:checked");
			var isSelected = '';
			if(selected.length>0){
				isSelected = 'true';		
			}
			var url ='iframe:resource/res-query!ipChange.action?isSelected='+isSelected+'';
		    var opt =  {title:'IP变更',id:'ipChange',width:350,height:210,iframeScrolling:'no',submit:function(v, h, f){},buttons:{}};
		    getTopWin(window).openjBox(url,opt,'resIpChange',window);
		}
		
		function ipChange(entity){
			var ipValue = entity.selectedVal+'@'+entity.newIp ;
			if(entity.selectedVal==2){
				ipValue +='@'+entity.changeIp
			}else{
				var selected =$("input[name='resCheck']:checked");
				var resIds = '';
				$.each(selected,function(index,ob){
						resIds +=ob.value;
					if(index!=selected.length-1){
						resIds +=',';
					}
				});
				ipValue +='@'+resIds;
			}
				ipValue +='@'+entity.relation;
			getTopWin(window).getMessageBox().tip("IP变更中...", 'loading');
			 $.ajax({
					type:'post',
					url:'res-query!resIpChange.action',
					data:{ipValue:ipValue},
					global:false,
					async:false,
					cache:false,
					dataType:'json',
					success:function(data,textStatus){
						if(data.hasExitPrivalige==false){
							getTopWin(window).getMessageBox().tip(data.privaligeVlidateResult);
						}else{
							var oTable =$('#resList').dataTable();
							window.setTimeout(function () {
								getTopWin(window).getMessageBox().tip('IP变更成功。', 'success'); 
								oTable.fnClearTable(); 
								$("#allCheck").removeAttr("checked");
							},1500);
						}
					},
					error:function(errorOb,type){
						getTopWin(window).getMessageBox().alert('服务器内部错误,请联系管理员','错误');
					}
			  });
		}
		
		function openProbeChangeWindow(){
			var selected = $("input[name='resCheck']:checked");
			var isSelected = '';
			if(selected.length>0){
				isSelected = 'true';		
			}
			var url ='iframe:resource/res-query!probeChange.action?isSelected='+isSelected+'';
		    var opt =  {title:'采集器(Probe)变更',id:'probeChange',width:350,height:300,iframeScrolling:'no',submit:function(v, h, f){},buttons:{}};
		    getTopWin(window).openjBox(url,opt,'probeChange',window);
		}
		
		//变更probe
		probeChange = function(entity){
			var probeValue = entity.selectedVal+'@'+entity.newProbe;
			if(entity.selectedVal==2){
				probeValue +='@'+entity.currentProbe;
			}else{
				var selected =$("input[name='resCheck']:checked");
				var resIds = '';
				$.each(selected,function(index,ob){
						resIds +=ob.value;
					if(index!=selected.length-1){
						resIds +=',';
					}
				});
				probeValue +='@'+resIds;
			}
			probeValue +='@'+entity.relation;
			getTopWin(window).getMessageBox().tip("probe变更中...", 'loading');
			 $.ajax({
					type:'post',
					url:'res-query!resProbeChange.action',
					data:{probeValue:probeValue},
					global:false,
					async:false,
					cache:false,
					dataType:'json',
					success:function(data,textStatus){
						var oTable =$('#resList').dataTable();
						window.setTimeout(function () {
				            if(data.flag==false){
				            	getTopWin(window).getMessageBox().tip(data.info,"info");
				            }else{
				            	getTopWin(window).getMessageBox().tip('probe变更成功。', 'success'); 
						   		 oTable.fnClearTable(); 
				            }
							 $("#allCheck").removeAttr("checked");
						},1500);
					},
					error:function(errorOb,type){
						getTopWin(window).getMessageBox().alert('服务器内部错误,请联系管理员','错误');
					}
			  });
		}
		
		//资源名称变更时
		function resNameChange(){
			var cityObj = $("#name");
			var cityOffset = $("#name").offset();
			$("#sameResName").css({left:cityOffset.left + "px", top:cityOffset.top + cityObj.outerHeight() + "px"}).slideDown("fast");
			
			$('#sameResName').children("div").remove();
			//匹配值
			$.ajax({
					type:'post',
					url:'res!matching.action',
					data:{resName:cityObj.val()},
					global:false,
					async:false,
					cache:false,
					dataType:'json',
					success:function(data,textStatus){
						if(data!=null){
							$.each(data,function(index,ob){
								$('#sameResName').append("<div style='padding:3px;'>"+ob.substring(0,21)+"</div>");	
							});
						}
					},
					error:function(errorOb,type){
						getTopWin(window).getMessageBox().alert('服务器内部错误,请联系管理员','错误');
					}
			  });
			
			//绑定点击事件
			$('#sameResName div').bind('click',function(event){
				cityObj.val($(this).text());
			}).bind('mousemove',function(event){
				$(this).css('cursor','hand').css('background-color','#E8EFF8');
			}).bind('mouseout',function(event){
				$(this).css('cursor','hand').css('background-color','');
			});
			
			
			$("#name").live("blur", function(event){
				 if(event.target.id='name'){
					$('#sameResName').fadeOut("fast");
					$('#name').unbind('blur');
				 }
			});
		}
		
		function delChild(){
			var myparams = {};
			var selected =$("input[name='resCheck']:checked");
			myparams.Ids = new Array(selected.length);
			for(var i=0; i<selected.length; i++){
				myparams.Ids[i]=selected[i].value;
			}
			getTopWin(window).jBox.confirm("确定删除这些资源吗？", "提示", function(v, h, f){
				if (v == 'ok') {
					$.ajax({
						type:'post',
						url:'res!deleteByIsChildRes.action',
						data :jQuery.param(myparams,true),
						global:false,
						async:false,
						cache:false,
						dataType:'json',
						success:function(data,textStatus){
							var oTable=$('#resList').dataTable();
							var oSettings =oTable.fnSettings();
							oTable.fnPageChange(oSettings._iDisplayStart/oSettings._iDisplayLength);
						},
						error:function(errorOb,type){
							
						}
				  });
				}
			});
		}
    </script>
	</head>

	<body>
		<div class="searchFormStyle" id="searchParameter">
			<div id="dimensionDiv" style="display: none;" >
				<label>
					资源类别：
				</label>
				<span id="dimensionSearch"></span>
				<input type="hidden" id="dimension" name="dimension" />
			</div>
			<div style="margin-top: 5px;">
				<label>
					资 源 ID：
				</label>
				<input type="text" name="id" id="id" maxlength="16" class="input_text" />
				<label>
					&nbsp;资 源 IP：
				</label>
				<input type="text" name="ip" id="ip" maxlength="16" class="input_text" />
				<label>
					&nbsp;资源名称：
				</label>
				<input type="text" name="name" id="name" maxlength="20" class="input_text" onkeyup="resNameChange()" />
					
				<label>
					采集器：
				</label>
				<select name="probeId" id="probeId"
					style="width: 140px; text-align: center;">
					<option value="" title="">
						---- 请选择采集器 ----
					</option>
					<%
   						List<Probe> probes = (List<Probe>)request.getAttribute("probes");
   						for(Probe  p : probes){
   						    if(p.getStatus()==3){
   			    				out.println("<option value='"+p.getId()+"' title='/bsm/style/default/bsm/images/proberun.png' >"+p.getId()+"_"+p.getName()+"</option>");
   						    }else{
 	    			    		out.println("<option value='"+p.getId()+"' title='/bsm/style/default/bsm/images/probestop.png' >"+p.getId()+"_"+p.getName()+"</option>");
   						    }
   						}
	    			%>
				</select>
			</div>
			<div style="margin-top: 5px;">
				<label>
					监控状态：
				</label>
				<input id="pausedStatus" type="checkbox" name="paused" value="1" checked="checked" />
				<label for="pausedStatus" >
					已暂停
				</label>
				<input id="normalStatus" type="checkbox" name="paused" value="0" checked="checked" />
				<label for="normalStatus">
					正常监控
				</label>
				<label>
					健康状态：
				</label>
				<input id="normalHeal" type="checkbox" name="healthStatus" value="1"
					checked="checked" />
				<label for="normalHeal">
					<%=ResConstants.HEALTH_DESC[0] %>
				</label>
				<input id="basicHeal" type="checkbox" name="healthStatus" value="2"
					checked="checked" />
				<label for="basicHeal">
					<%=ResConstants.HEALTH_DESC[1] %>
				</label>
				<input id="middleHeal" type="checkbox" name="healthStatus" value="3"
					checked="checked" />
				<label for="middleHeal">
					<%=ResConstants.HEALTH_DESC[2] %>
				</label>
				<input id="fewHeal" type="checkbox" name="healthStatus" value="4"
					checked="checked" />
				<label for="fewHeal">
					<%=ResConstants.HEALTH_DESC[3] %>
				</label>
				<input id="noHeal" type="checkbox" name="healthStatus" value="5"
					checked="checked" />
				<label for="noHeal">
					<%=ResConstants.HEALTH_DESC[4] %>
				</label>
				<input type="button" value="查询" class="searchFormButtonStyle"  onclick="search()"/>
			</div>
		</div>

		<h2 class="title-h2">
			<span><img
					src="${pageContext.request.contextPath}/style/default/bsm/images/arrow-down.gif" />
			</span>资源查询列表
		</h2>
		<div id="resDiv">
		  <%if(UserFunctionValidate.sysFunctionValidate(FunctionConstants.SYSTEM_MANAGER)){%>
			<div class="toolbar" id="toolbar">
				<!-- <a class="page_excel" href="#">导出</a>
				<span class="page_s">&nbsp;</span> -->
				<a class="page_edit" href="#" onclick="openIpChangeWindow();">IP变更</a>
				<span class="page_s">&nbsp;</span>
				<a class="page_edit" href="#" onclick="openProbeChangeWindow()">Probe变更</a>
				<span class="page_s">&nbsp;</span>
				 <a class="page_delete" href="#" onclick="delChild()">删除</a>
			</div>
		  <%}%>
			<table cellpadding="0" cellspacing="0" border="0" class="display"
				id="resList" width="100%">
				<thead>
					<tr>
						<th width="1%">&nbsp;&nbsp;<input type="checkbox" id="allCheck" onclick="allSelected()" /></th>
						<th width="5%">资源类别</th>
						<th width="4%">资源IP</th>
						<th width="2%">健康状态</th>
						<th width="5%">采集器</th>
						<th width="10%">资源名称</th>
						<th width="5%">监控状态</th>
					</tr>
				</thead>
			</table>
		</div>
		<div id="sameResName" style="display: none; position: absolute; width: 130px; height: 170px; background-color: #ffffff;"></div>
		<div id="menuContent" class="menuContent" style="display: none; position: absolute;">
			<ul id="resTypeTree" class="ztree" style="margin-top: 0; padding-left: 0; width: 220px; height: 350px;"></ul>
		</div>
	</body>
</html>
